<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Image</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f4f4f4;
        }
        .container {
            text-align: center;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            background-color: white;
        }
        .preview img {
            max-width: 100%;
            max-height: 300px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="preview" id="imagePreview">
        <!-- 动态显示上传后的图片 -->
    </div>
    <h2>选择图片上传</h2>
    <form id="uploadForm">
        <input type="file" name="image" accept="image/*" required>
        <button type="submit">上传</button>
    </form>
</div>

<script>
    document.getElementById('uploadForm').addEventListener('submit', function(event) {
        event.preventDefault(); // 阻止表单的默认提交行为

        var form = event.target;
        var formData = new FormData(form);

        fetch('http://localhost:8080/upload', {
            method: 'POST',
            body: formData,
        })
            .then(response => response.json()) // 假设服务器返回JSON响应
            .then(data => {
                alert('上传成功: ' + JSON.stringify(data));
                // 更新预览图片
                const imageUrl = 'http://localhost:8080/' + data.message; // 假设返回的数据中包含图片的相对路径
                document.getElementById('imagePreview').innerHTML = `<img src="${imageUrl}" alt="Uploaded Image">`;
            })
            .catch((error) => {
                console.error('Error:', error);
                alert('上传失败: ' + error.message);
            });
    });

    // 实现图片选择后的即时预览
    document.querySelector('input[name=image]').addEventListener('change', function() {
        const input = this;
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('imagePreview').innerHTML = `<img src="${e.target.result}" alt="Image Preview">`;
            };
            reader.readAsDataURL(input.files[0]);
        }
    });
</script>
</body>
</html>